from django.shortcuts import render

# Create your views here.
from django.views import View
from django.contrib.auth import authenticate
#系统封装的验证方法

class TestView(View):

    def get(self, request):
        pass

    def post(self, request):
        pass

    def put(self, request):
        pass

    def delete(self, request):
        pass


from django.views.generic.base import View

from django.http import JsonResponse
import re
import json
from django.contrib.auth import login,logout
from django.contrib.auth.mixins import LoginRequiredMixin
from common.views import LoginRequiredJSONMixin
from django.core.mail import send_mail
from apps.users.common import check_email_token
from apps.users.models import User,Address
from apps.goods.models import SKU
from django_redis import get_redis_connection


class UsernameCountView(View):
    def get(self, request, username):

        # if re.match('[a-zA-Z0-9]{5,20}',username) :
        #     return JsonResponse({'code':400,'errmsg':'用户名无效'})



        count = User.objects.filter(username=username).count()
        #返回响应
        return JsonResponse({'code':0,'errmsg':'ok','count':count})



class CellphoneCountView(View):
    def get(self, request, phonenum):
        if not re.match('1[3-9]\d{9}',phonenum):
            return JsonResponse({'code':400,'errmsg':'号码格式错误'})

        count_ph = User.objects.filter(phonenum=phonenum).count_ph()
        return JsonResponse({'code':0,'errmsg':'ok','count_ph':count_ph})


class RegisterView(View):
    def post(self,request):
#1接收数据 2验证数据 3数据入库 4返回响应


        body_str=request.body.decode()
        body_dict=json.loads(body_str)

        username=body_dict.get('username')
        password=body_dict.get('password')
        mobile=body_dict.get('mobile')

        user=User.objects.create_user(username=username,password=password,mobile=mobile)


        login(request, user)
        return JsonResponse({'code':0,'errmsg':'done'})

from apps.carts.common import merge_cookie_to_redis
class LoginView(View):
    def post(self,request):
        #请求 业务逻辑 响应
        data=json.loads(request.body.decode())
        username=data.get('username')
        password=data.get('password')
        remember=data.get('remembered')
       #验证
        if not all([username, password]):
            return JsonResponse({'code':400,'errmsg':'参数不全'})

#django用户认证不支持手机号登录，需要修改   默认是用户名
        if re.match('1[3-9]\d{9}',username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD='username'


        user=authenticate(username=username,password=password)
        if user is None:
            return JsonResponse({'code':400,'errmsg':'用户名或密码错误'})

        #状态保持
        login(request,user)
        #记得登录状态
        if remember:
            request.session.set_expiry(None) #默认None为两周
        else:
            request.session.set_expiry(0)  #过期关闭

        response=JsonResponse({'code':0,'errmsg':'done'})

        #合并购物车数据
        response=merge_cookie_to_redis(request,response)


            #cookie: key, value, 有效期   （用户名的显示）
        response.set_cookie('username',user.username,max_age=14*24*3600)
        return response

class LogoutView(View):
    def delete(self,request):
        #只删了session 还有cookie
        logout(request)
        response=JsonResponse({'code':0,'errmsg':'done'})
        response.delete_cookie('username')

        return response


class UserCenterView(LoginRequiredMixin,View):
    def get(self,request):

        #用户信息
        info_data={
            'username':request.user.username,
            'mobile':request.user.mobile,
            'email':request.user.email,
            'email_active':request.user.email_active

        }
        return JsonResponse({'code':0,'info_data':info_data})

#保存邮箱，给它发一个邮箱激活(请求，业务逻辑，响应）

class EmailView(LoginRequiredJSONMixin,View):

    def put(self,request):
        data=json.loads(request.body.decode())
        email=data.get('email')

        request.user.email=email #来自settings 的session信息
        request.user.save()

        # subject='最强长谷川一志登录美多'
        # message=''
        # from_email='长谷川一志<qi_rui_hua@163.com>'
        # recipient_list=[email]
        #
        # from apps.users.common import generic_email_access_token
        # access_token=generic_email_access_token(request.user.id,email)
        #
        #
        # verify_url='http://www.meiduo.site:8080/success_verify_email.html?token=%s'%access_token
        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (email,verify_url,verify_url)
        #
        #
        # send_mail(subject,message,from_email,recipient_list,html_message=html_message)

        from apps.users.common import generic_email_access_token
        access_token=generic_email_access_token(request.user.id,email)

        from celery_tasks.email.tasks import celery_send_mail
        celery_send_mail.delay(email,access_token)


        return JsonResponse({'code':0,'errmsg':'邮件已保存'})



class EmailVerificationView(View):#邮件激活
    def put(self,request):
#1 接收参数 2 验证参数 3 解密token 4 获取邮箱和用户id 5 根据邮箱id进行查询
#改变邮箱状态 响应
        token=request.GET.get('token')
        if token is None:
            return JsonResponse({'code':400,'errmsg':'参数缺失'})


        data=check_email_token(token)
        if data is None:
            return JsonResponse({'code':400,'errmsg':'token过期'})

        #data = {id,email}
        user_id=data.get('id')
        email=data.get('email')

        try:
            user=User.objects.get(id=user_id,email=email)
        except User.DoesNotExist:

            return JsonResponse({'code': 400, 'errmsg': '用户不存在'})

        user.email_active=True
        user.save()
        return JsonResponse({'code':0,'errmsg':'done'})


#需求：实现地址保存
#请求post   业务逻辑（接收，验证，入库，返回响应
#json格式 code address id city province
class AddressCreateView(LoginRequiredJSONMixin,View): #登录用户操作，继承
    def post(self,request):
        json_dict=json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        address=Address.objects.create(
            user=request.user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email

         )

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code': 0, 'errmsg': '新增地址成功', 'address': address_dict})


class AddressesView(LoginRequiredJSONMixin,View):
    def get(self,request):
    #查询用户地址信息，遍历查询结果集，返回
        addresses=Address.objects.filter(user=request.user)
        addresses_dict=[]
        for address in addresses:
            addresses_dict.append({
                    "id": address.id,
                    "title": address.title,
                    "receiver": address.receiver,
                    "province": address.province.name,
                    "city": address.city.name,
                    "district": address.district.name,
                    "place": address.place,
                    "mobile": address.mobile,
                    "tel": address.tel,
                    "email": address.email

                })
        return JsonResponse({'code': 0, 'addresses': addresses_dict})


#浏览记录添加
#请求 POST 传sku_id
#接收请求参数，验证请求，连接redis,去重，后储存，再截取，返回
class UserHistoryView(View):
    def post(self,request):
        data=json.loads(request.body.decode())
        sku_id=data.get('sku_id')
        try:
            sku=SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400,'errmsg':'无此商品'})

        redis_cli=get_redis_connection('history')
        redis_cli.lrem('history_%s'%request.user.id,0,sku_id)
        redis_cli.lpush('history_%s'%request.user.id,sku_id)
        redis_cli.ltrim('history_%s' % request.user.id,0.4)
        return JsonResponse({'code': 0,'errmsg':'done'})

    def get(self,request):

#获取用户浏览记录
#获取登录用户信息，获取列表数据，根据sku_id查询信息，将对象转换字典，返回
        user=request.user
        redis_cli=get_redis_connection('history')
        sku_ids=redis_cli.lrange('history_%s'%user.id,0,-1)
        # skus=SKU.objects.filter(id_in=sku_ids)

        sku_list=[]
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append({
                'id':sku.id,
                'price':sku.price,
                'name':sku.name,
                'default_image_url':sku.default_image.url
            })

        return JsonResponse({'code': 0,'skus':sku_list,'errmsg':'done'})









































